#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据迁移脚本：将JSON文件数据迁移到SQLite数据库
"""

import json
import os
from pathlib import Path
from database import db_manager, user_db, chat_history_db, PasswordManager

def migrate_users():
    """迁移用户数据"""
    print("开始迁移用户数据...")
    
    users_file = 'data/users.json'
    if not os.path.exists(users_file):
        print("用户数据文件不存在，跳过迁移")
        return
    
    try:
        with open(users_file, 'r', encoding='utf-8') as f:
            users_data = json.load(f)
        
        migrated_count = 0
        for user_data in users_data:
            try:
                # 检查用户是否已存在
                existing_user = user_db.get_user_by_student_id(user_data['student_id'])
                if existing_user:
                    print(f"用户 {user_data['student_id']} 已存在，跳过")
                    continue
                
                # 创建用户（密码会被重新加密）
                success, message = user_db.create_user(
                    student_id=user_data['student_id'],
                    name=user_data['name'],
                    password=user_data.get('password', '123456'),  # 默认密码
                    college=user_data.get('college', '计算机科学与技术学院'),
                    major=user_data.get('major', '人工智能'),
                    phone=user_data.get('phone')
                )
                
                if success:
                    # 更新额外的用户信息
                    user_db.update_user(
                        user_data['student_id'],
                        profile=user_data.get('profile'),
                        avatar_url=user_data.get('avatar_url', 'images/default_avatar.jpeg')
                    )
                    
                    # 更新简历信息
                    if user_data.get('resume'):
                        user_db.update_resume(user_data['student_id'], user_data['resume'])
                    
                    # 更新未读通知
                    if user_data.get('unread_news'):
                        user_db.update_unread_news(user_data['student_id'], user_data['unread_news'])
                    
                    migrated_count += 1
                    print(f"✅ 成功迁移用户: {user_data['student_id']} - {user_data['name']}")
                else:
                    print(f"❌ 迁移用户失败: {user_data['student_id']} - {message}")
                    
            except Exception as e:
                print(f"❌ 迁移用户 {user_data.get('student_id', 'unknown')} 时出错: {e}")
        
        print(f"用户数据迁移完成，共迁移 {migrated_count} 个用户")
        
    except Exception as e:
        print(f"迁移用户数据时出错: {e}")

def migrate_chat_history():
    """迁移聊天历史数据"""
    print("开始迁移聊天历史数据...")
    
    chat_history_file = 'data/chat_history.json'
    if not os.path.exists(chat_history_file):
        print("聊天历史文件不存在，跳过迁移")
        return
    
    try:
        with open(chat_history_file, 'r', encoding='utf-8') as f:
            chat_histories = json.load(f)
        
        migrated_count = 0
        for history_data in chat_histories:
            student_id = history_data['student_id']
            conversations = history_data.get('conversations', [])
            
            for conversation_data in conversations:
                try:
                    # 创建对话
                    conversation_id = chat_history_db.create_conversation(
                        student_id, 
                        conversation_data['title']
                    )
                    
                    if conversation_id:
                        # 添加消息
                        messages = conversation_data.get('messages', [])
                        for message_data in messages:
                            success = chat_history_db.add_message(
                                conversation_id,
                                message_data['type'],
                                message_data['content']
                            )
                            if not success:
                                print(f"❌ 添加消息失败: {conversation_id}")
                                break
                        
                        migrated_count += 1
                        print(f"✅ 成功迁移对话: {conversation_id} - {conversation_data['title']}")
                    else:
                        print(f"❌ 创建对话失败: {conversation_data['title']}")
                        
                except Exception as e:
                    print(f"❌ 迁移对话时出错: {e}")
        
        print(f"聊天历史迁移完成，共迁移 {migrated_count} 个对话")
        
    except Exception as e:
        print(f"迁移聊天历史时出错: {e}")

def backup_json_files():
    """备份原始JSON文件"""
    print("备份原始JSON文件...")
    
    backup_dir = 'data/backup'
    os.makedirs(backup_dir, exist_ok=True)
    
    files_to_backup = [
        'data/users.json',
        'data/chat_history.json'
    ]
    
    for file_path in files_to_backup:
        if os.path.exists(file_path):
            backup_path = os.path.join(backup_dir, os.path.basename(file_path))
            try:
                import shutil
                shutil.copy2(file_path, backup_path)
                print(f"✅ 已备份: {file_path} -> {backup_path}")
            except Exception as e:
                print(f"❌ 备份失败 {file_path}: {e}")

def main():
    """主迁移函数"""
    print("=" * 50)
    print("开始数据迁移：JSON -> SQLite")
    print("=" * 50)
    
    # 备份原始文件
    backup_json_files()
    
    # 迁移用户数据
    migrate_users()
    
    # 迁移聊天历史
    migrate_chat_history()
    
    print("=" * 50)
    print("数据迁移完成！")
    print("原始JSON文件已备份到 data/backup/ 目录")
    print("新的SQLite数据库文件位置: data/app.db")
    print("=" * 50)

if __name__ == '__main__':
    main()
